package com.histone.heartbeat.service;

import com.alibaba.fastjson.JSONObject;
import com.histone.heartbeat.dao.UserDao;
import com.histone.heartbeat.pojo.UserEntity;
import com.histone.heartbeat.pojo.WxApi;
import com.histone.heartbeat.pojo.WxProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.validation.constraints.NotNull;

@Service
@Slf4j
public class UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private WxApi wxApi;

    @Autowired
    private WxProperties wxProperties;

    /**
     * 通过code换取openid， 可将code缓存，避免用户刷新页面导致同一code消费两次
     * @param code
     * @return
     */
    public String getOpenid(String code) {
        String url = wxApi.getOpenid().replaceAll("APPID", wxProperties.getAppid())
                .replaceAll("SECRET", wxProperties.getSecret())
                .replaceAll("CODE", code);
        JSONObject result = restTemplate.getForObject(url, JSONObject.class);
        log.info("get openid result is {}", result);
        if(result.getInteger("errcode") == null){
            return result.getString("openid");
        } else {
            return "";
        }
    }

    public UserEntity getUser(@NotNull String userid) {
        return userDao.findById(userid).get();
    }

    public UserEntity updateUser(UserEntity userEntity) {
        return userDao.save(userEntity);
    }

}
